package leetcode_2101_2200;

import java.nio.channels.SeekableByteChannel;
import java.util.*;

public class LeeCode_2192 {
    public static void main(String[] args) {

    }
    private static List<List<Integer>> getAncestors(int n, int[][] edges) {
        List<List<Integer>> ans = new ArrayList<>();
        List<Set<Integer>> demo = new ArrayList<>();
        int[] system = new int[n];
        int[][] grid = new int[n][n];
        for (int[] edge : edges) {
            system[edge[1]]++;
            grid[edge[0]][edge[1]] = 1;
        }
        Queue<Integer> queue = new LinkedList<>();
        for (int i = 0; i < n; i++) {
            if (system[i] == 0){
                queue.offer(i);
                system[i]--;
            }
            ans.add(new ArrayList<>());
            demo.add(new TreeSet<>());
        }
        while (!queue.isEmpty()){
            int size = queue.size();
            while (size-- > 0){
                int idx = queue.poll();
                for (int i = 0; i < n; i++) {
                    if (grid[idx][i] == 1){
                        system[i]--;
                        demo.get(i).add(idx);
                        demo.get(i).addAll(demo.get(idx));
                    }
                    if (system[i] == 0){
                        queue.add(i);
                        system[i]--;
                    }
                }
            }
        }
        for (int i = 0; i < n; i++) {
            ans.get(i).addAll(demo.get(i));
        }
        return ans;
    }
}
